<template>
  <el-dialog
    title="从正文中选择图片"
    :visible.sync="dialogVisible"
    width="1000px"
    :close-on-click-modal="false"
    :lock-scroll="false"
    append-to-body
  >
    <div class="img-wrap">
      <el-row :gutter="20">
        <el-col :span="6" v-for="(v, i) in imgSrcArr" :key="i">
          <div
            :class="['img-box', { active: v == selected }]"
            @click="selected = v"
          >
            <img :src="v" alt="" />
          </div>
        </el-col>
      </el-row>
    </div>
    <span slot="footer" class="dialog-footer">
      <el-button @click="dialogVisible = false">取 消</el-button>
      <el-button type="primary" @click="handleSubmit()">确 定</el-button>
    </span>
  </el-dialog>
</template>
<script>
export default {
  data() {
    return {
      dialogVisible: false,
      content: '',
      imgSrcArr: [],
      selected: '',
    }
  },
  mounted() {
    this.$bus.$on('selectImgFromArticle', (v) => {
      this.content = v
      this.selectImg()
    })
  },
  beforeDestroy() {
    this.$bus.$off('selectImgFromArticle')
  },
  methods: {
    selectImg() {
      this.imgSrcArr = this.cut()
      if (!this.imgSrcArr.length) {
        this.warnMsg('正文中没有图片,请先在正文中添加！')
        return
      }
      this.dialogVisible = true
    },
    handleSubmit() {
      if (!this.selected) {
        this.warnMsg('请选择图片')
        return
      }
      this.$emit('e-emit', this.selected)
      this.dialogVisible = false
    },
    cut() {
      let imgReg = /<img.*?(?:>|\/>)/gi //匹配图片中的img标签
      let srcReg = /src=[\'\"]?([^\'\"]*)[\'\"]?/i // 匹配图片中的src
      let str = this.content //数据源
      let arr = str.match(imgReg) //筛选出所有的img
      let srcArr = []
      if (arr) {
        for (let i = 0; i < arr.length; i++) {
          let src = arr[i].match(srcReg)
          // 获取图片地址
          srcArr.push(src[1])
        }
      }
      return srcArr
    },
  },
}
</script>
<style scoped lang="scss">
.img-wrap {
  min-height: 300px;
  max-height: 500px;
  overflow-y: auto;
  overflow-x: hidden;
}
.img-box {
  padding: 10px;
  width: 100%;
  height: 200px;
  border-radius: 5px;
  border: 1px solid #eee;
  box-sizing: border-box;
  margin-bottom: 20px;
  cursor: pointer;
  &.active {
    border: 3px solid $mainColor;
  }
  img {
    display: block;
    width: 100%;
    height: 100%;
  }
}
</style>